import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import os

# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用SimHei字体
plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号


def main():
    if not os.path.exists("images"):
        os.makedirs("images")
    # 读取数据
    file_path = "../lottery/csv/dlt_lottery_numbers.csv"
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"未找到数据文件: {file_path}")

    df = pd.read_csv(file_path)

    # 转换星期为中文
    weekday_map = {0: "周一", 2: "周三", 5: "周六"}
    df["星期"] = df["星期"].map(weekday_map)

    # 提取前区后区号码
    front_cols = ['前区1', '前区2', '前区3', '前区4', '前区5']
    back_cols = ['后区1', '后区2']

    # 确保所有号码都是字符串并补齐两位
    for col in front_cols + back_cols:
        df[col] = df[col].apply(lambda x: f"{int(x):02d}" if isinstance(x, (int, float)) else x)

    # 1. 按开奖日分组统计销售额
    grouped = df.groupby("星期")
    sales_stats = grouped["销售金额"].agg(["sum", "mean", "count"])
    sales_stats["平均销售额(亿元)"] = sales_stats["mean"] / 100000000

    # 2. 号码分布统计
    def get_number_distribution(df, cols, num_range):
        # 计算号码分布频率
        all_nums = df[cols].values.flatten()
        freq = pd.Series(all_nums).value_counts().reindex(num_range, fill_value=0)
        return freq / len(df)

    # 创建号码范围
    front_num_range = [f"{i:02d}" for i in range(1, 36)]
    back_num_range = [f"{i:02d}" for i in range(1, 13)]

    # 计算各开奖日的号码分布
    distributions = {}
    for day in ["周一", "周三", "周六"]:
        day_df = df[df["星期"] == day]
        distributions[day] = {
            "前区": get_number_distribution(day_df, front_cols, front_num_range),
            "后区": get_number_distribution(day_df, back_cols, back_num_range)
        }

    # 3. 创建图表
    plt.figure(figsize=(14, 12))

    # 销售额对比图
    plt.subplot(3, 1, 1)
    sales_data = sales_stats["平均销售额(亿元)"].sort_index()
    days = sales_data.index
    values = sales_data.values

    bars = plt.bar(days, values, color=['#1f77b4', '#ff7f0e', '#2ca02c'])
    plt.title('不同开奖日平均销售额对比', fontsize=14)
    plt.ylabel('平均销售额 (亿元)', fontsize=12)
    plt.ylim(0.3, max(values) * 1.15)
    plt.grid(axis='y', linestyle='--', alpha=0.7)

    for bar in bars:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2., height,
                 f'{height:.3f}', ha='center', va='bottom')

    # 前区号码分布图 - 使用热力图展示
    plt.subplot(3, 1, 2)
    # 准备热力图数据
    heatmap_data = []
    for day in ["周一", "周三", "周六"]:
        heatmap_data.append(distributions[day]["前区"].values * 100)
    heatmap_data = np.array(heatmap_data)

    # 创建热力图
    sns.heatmap(heatmap_data,
                annot=True,
                fmt=".1f",
                cmap="YlGnBu",
                xticklabels=front_num_range,
                yticklabels=["周一", "周三", "周六"])
    plt.title('前区号码出现频率 (%)', fontsize=14)
    plt.xlabel('前区号码', fontsize=12)
    plt.ylabel('开奖日', fontsize=12)

    # 后区号码分布对比图
    plt.subplot(3, 1, 3)
    bar_width = 0.25
    index = np.arange(len(back_num_range))

    colors = {'周一': '#1f77b4', '周三': '#ff7f0e', '周六': '#2ca02c'}

    for i, day in enumerate(["周一", "周三", "周六"]):
        plt.bar(index + i * bar_width,
                distributions[day]["后区"].values * 100,
                width=bar_width,
                label=day,
                color=colors[day])

    plt.title('后区号码出现频率对比 (%)', fontsize=14)
    plt.xlabel('后区号码', fontsize=12)
    plt.ylabel('出现频率 (%)', fontsize=12)
    plt.xticks(index + bar_width, back_num_range)
    plt.legend()
    plt.grid(axis='y', linestyle='--', alpha=0.7)

    plt.tight_layout()
    plt.savefig('images/dlt_analysis_results.png', dpi=300, bbox_inches='tight')
    plt.show()


if __name__ == "__main__":
    main()